﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WpfApplication1;
using System.Reflection;
using CodeMonkey.EditableObject.Core;
using GalaSoft.MvvmLight.Command;

namespace BindingOriented.Adapters.Demo.ObjectModel
{
    public class EditableContact : EditableModelBase<Contact>
    {
        public IEnumerable<ValueDescription> SexyList
        { get { return EnumHelper.GetAllValuesAndDescriptions<Sexy>(); } }

        public EditableContact(Contact contact)
            : base(contact)
        {
            ApplyChangesCommand = new RelayCommand(() => { EndEdit(); });
            CancelChangesCommand = new RelayCommand(() => { CancelEdit(); });
        }

        public RelayCommand ApplyChangesCommand { get; private set; }
        public RelayCommand CancelChangesCommand { get; private set; }
        

        //一律将需要验证的属属性的属性值的获取方法GetPropertyValue<TProperty>(string)方法中的TProperty设置为string
        //用作基准的属性则采用原来的类型
        protected override string ValidateProperty(string prop)
        {
            switch (prop)
            {
                case "FirstName":
                    string val = GetPropertyValue<string>(prop); //可能出现泛型类型选择错误;比如把FirstName被认为是int类型;导致基类中转型失败
                    if (string.IsNullOrEmpty(val))
                    {
                        return "FirstName不能为空";
                    }
                    var d = MainWindow.dd.FirstOrDefault(s => s.FirstName == val && s.ID != GetPropertyValue<int>("ID"));//GetPropertyValue<int>("ID")(() => wrappedObject.ID)
                    if (d != null)
                    {
                        return "不能重复";
                    }
                    break;
                case "LastName":
                    val = GetPropertyValue<string>(prop);
                    if (string.IsNullOrEmpty(val))
                    {
                        return "LastName不能为空";
                    }
                    break;
                case "Age":
                    //double valint = GetPropertyValue<double>(prop);
                    string valint = GetPropertyValue<string>(prop);
                    double ageNow;
                    if (! double.TryParse(valint,out ageNow))
                    {
                        return "年龄必须是数值";
                    }
                    if (ageNow < 0)
                    {
                        return "Age不能小于零";
                    }
                    if (GetPropertyValue<double>("AgeLarge") <= ageNow) //"AgeLarge"
                    {
                        return "Age不能大于AgeLarge";
                    }
                    break;
                default:
                    break;
            }
            return string.Empty;
        }
    }
}
